#include "ServerSessionMgr.h"
#include "Server.h"
#include <list>

using namespace car;

ServerSessionMgr::ServerSessionMgr(void)
{
}

ServerSessionMgr::ServerSessionMgr( Server * server )
{
	if( server )
		mServer = server;
}

ServerSessionMgr::~ServerSessionMgr(void)
{
}

bool ServerSessionMgr::startSession()
{
	return mConnection.start( 30000 );
}

void ServerSessionMgr::stopSession()
{
	mConnection.close();
}

void ServerSessionMgr::update( float deltaTime )
{
	if( mServer )
	{
		unsigned char data[256];
		unsigned char roomListData[256];
		int roomListDataSize = 0;

		while( true )
		{
			LASAddress address;
			int receivedBytes = mConnection.receivePacket( address, &data[0], 256 );
			if( receivedBytes > 0 )
			{
				printf( "receive packet\n" );
				PacketHandler::handlePacket( address, mServer, data, receivedBytes );
			}
			else
				break;
		}

		std::list<Player *> playerList = mServer->getPlayerList();
		for( std::list<Player *>::iterator itr = playerList.begin(); itr != playerList.end(); ++itr )
		{
			Player * player = ( *itr );
			int receivedBytes = player->receivePacket( data, 256 );
			LASAddress address;
			if( receivedBytes > 0 )
				PacketHandler::handlePacket( address, mServer, data, receivedBytes );
			player->setPacketSent( false );
		}

		std::list<Room *> roomList = mServer->getRoomList();
		for( std::list<Room *>::iterator itr = roomList.begin(); itr != roomList.end(); ++itr )
		{
			Room * room = ( *itr );
			if( room )
				room->checkPlayerLoadingProgress();
		}

		for( std::list<Player *>::iterator itr = playerList.begin(); itr != playerList.end(); ++itr )
		{
			Player * player = ( *itr );

			switch( player->getPlayerState() )
			{
			case PlayerStateInHall:
				{
					if( !player->isPacketSent() )
					{
						if( roomListDataSize == 0 )
						{							
							roomListDataSize = PacketHandler::wrapRoomListPacket( mServer, player, roomListData, 256 );
						}
						if( roomListDataSize > 0 )
						{
							printf( "send packet\n" );
							player->sendPacket( roomListData, roomListDataSize );
						}	
					}
					break;
				}
			case PlayerStateInRoom:
			case PlayerStateLoadingGame:
			case PlayerStateLoadingGameComplete:
			case PlayerStateInGame:
			case PlayerStateGameEnd:
				{
					if( !player->isPacketSent() )
					{
						Room * room = mServer->getRoom( player->getRoomId() );
						if( room )
						{
							int size = PacketHandler::wrapRoomPacket( room, data, 256 );
							if( size > 0 )
								room->spreadPacket( data, size );
						}
					}
					break;
				}
			default:
				break;
			}
		}
		roomListDataSize = 0;
	}
}
